﻿using System.Linq;
using System.Windows.Forms;

namespace N2.Explorer.Services
{
	using Castle;

	class ViewService: IStudioService
	{
		public void Initialize(IStudioForm form)
		{
			var _iconService = ConfigurationService.Container.Resolve<IconService>();
			
			((Form)form).Load += (_sender, _e) => {
				form.TreeView.SuspendLayout();
				ContentItem _item = null;
				TreeNode _rootNode = null;

				do {
					try {
						_item = Find.RootItem;
						_rootNode = _item.ToTreeNode(true);

						break;
					} catch (NHibernate.WrongClassException) {

					}

					if (!ConfigurationService.LetUserReconfigureSession()) {
						Application.Exit();
					}
				} while (null == _rootNode);

				_rootNode.ContextMenuStrip = form.ContextMenu;
				_iconService.AssignIcons(_item, _rootNode);

				form.TreeView.Nodes.Add(_rootNode);
				form.TreeView.ResumeLayout();
			};

			form.TreeView.BeforeExpand += (_sender, _e) => {
				form.TreeView.SuspendLayout();
				var _nodeList = _e.Node.Nodes.Cast<TreeNode>().ToList();

				//assign context menu
				_nodeList.ForEach(_node => _node.ContextMenuStrip = form.ContextMenu);

				//add grandchildren to children
				_nodeList.ForEach(_node => _node.Populate((_item, _child) => {
					_child.ContextMenuStrip = form.ContextMenu;
					_iconService.AssignIcons(_item, _child);
					return _child;
				}));

				form.TreeView.ResumeLayout();
			};

			form.TreeView.AfterSelect += (_sender, _e) => {
				var _selectedItem = form.PropertyGrid.SelectedObject as ContentItem;

				if (_e.Node.Tag is int) {
					var _nodeId = (int)_e.Node.Tag;

					if ((null != _selectedItem && _selectedItem.ID != _nodeId)
						|| null == _selectedItem) {
						form.PropertyGrid.SelectedObject = Context.Persister.Get(_nodeId);
					}
				}
			};
		}
	}
}
